package com.wontube.core.pub;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import com.wontube.client.extension.utils.StringUtils;
import com.wontube.client.modle.vo.ClientSession;
import com.wontube.core.cache.CacheConf;
import com.wontube.core.cache.Cacher;
import com.wontube.core.cache.EHCacheKey;

/**
 * @author yuechao
 *
 */
public final class SessionManager {
	private static final String cacheName = "__u__core_pub_client_session";
	private static final int timeToLiveSeconds = 20 * 60;
	private static final int timeToIdleSeconds = 20 * 60;
	
	private final Cacher cacher = Cacher.defaultCacher;
	
	public static final SessionManager manager = new SessionManager();

	private SessionManager() {
	}
	
	/**
	 *  获取 session
	 *  
	 * @param sessionId
	 * @return
	 */
	public final ClientSession getSession(String sessionId) {
		return this.getSession(sessionId, false);
	}
	
	/**
	 * 获取 session
	 * 
	 * @param sessionId
	 * @param createNew
	 * @return
	 */
	public final ClientSession getSession(String sessionId, boolean createNew) {
		ClientSession session = this.cacher.<ClientSession>getCache(cacheName, new EHCacheKey(new Object[] { sessionId }));
		if (session == null && createNew) {
			if (StringUtils.isNullOrEmpty(sessionId)) {
				sessionId = UUID.randomUUID().toString();
			} else if (sessionId.startsWith("__$__")) {
				sessionId = sessionId.substring("__$__".length());
			}
			
			session = new ClientSession(sessionId);
		}
		
		return session;
	}
	
	/**
	 * 更新session缓存
	 * 
	 * @param sessionId
	 * @param value
	 * @return
	 */
	public boolean putSession(String sessionId, ClientSession value) {
		CacheConf conf = new CacheConf(timeToLiveSeconds, timeToIdleSeconds);		
		return this.cacher.putCache(cacheName, new EHCacheKey(new Object[] { sessionId }), conf, value);
	}
	
	/**
	 * 删除session缓存
	 * 
	 * @param sessionId
	 * @return
	 */
	public boolean deleteSession(String sessionId) {
		return this.cacher.deleteCache(cacheName, new EHCacheKey(new Object[] { sessionId }));
	}
	
	/**
	 * all session
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<ClientSession> listSessions() {
		List<?> list = this.cacher.listCache(cacheName);
		return (List<ClientSession>)list;
	}
	
	/**
	 * all sessions, filter by agent
	 * 
	 * @param agent
	 * @return
	 */
	public List<ClientSession> listSessionsByAgent(String agent) {
		if (agent == null) {
			return this.listSessions();
		}
		
		List<ClientSession> listResult = new ArrayList<ClientSession>();
		List<ClientSession> list = this.listSessions();
		for (ClientSession session : list) {
			if (agent.equals(session.getLastAgent())) {
				listResult.add(session);
			}
		}
		
		return listResult;
	}
	
	/**
	 * 所有session数量
	 * 
	 * @return
	 */
	public int getSessionCount() {
		return Cacher.defaultCacher.getCacheCount(cacheName);
	}
}
